package com.codexsoft.test;

import com.codexsoft.test.entities.User;
import com.codexsoft.test.jpamodel.EMF;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.PropertyModel;
import javax.persistence.EntityManager;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: Admin
 * Date: 26.08.11
 * Time: 10:15
 * To change this template use File | Settings | File Templates.
 */
public class AuthorizationPanel extends Panel {
    TextField nickname;
    TextField password;

    public AuthorizationPanel(String id){
        super(id);
        Form form = new Form("authorizationform");
        nickname = new TextField("nickname", new PropertyModel(this, ""));
        nickname.setModelObject("");
        password = new TextField("password", new PropertyModel(this, ""));
        password.setModelObject("");
        form.add(nickname);
        form.add(password);
        form.add(new Button("loginbutton") {
            @Override
            public void onSubmit() {
                String unick = (String) nickname.getModelObject();
                String upassword = (String) password.getModelObject();
                nickname.setModelObject("");
                password.setModelObject("");
                EntityManager em = EMF.get().createEntityManager();
                String query = "SELECT FROM " + User.class.getName();
                List<User> userList = em.createQuery(query).getResultList();
                try {
                    for(User u :userList)
                        if((u.getNickname().equals(unick)) && (u.getPassword().equals(upassword))){
                            u.setLogged(true);
                            em.merge(u);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    em.close();
                }
            }
        });
            form.add(new Label("registrationquestion", "haven't registered yet?"));
            form.add(new WizardLink("registrationprompt", RegistrationWizard.class));
        add(form);
    }

}
